package com.jason.quectel0805.activities;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.jason.quectel0805.R;
import com.jason.quectel0805.adapters.MyAdapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author：Jason
 * @date: 2022/8/9 10:30
 * @email：1129847330@qq.com
 * @description: recyclerview三剑客：RecyclerView、Adapter、list数据源
 */
public class RecyclerViewActivity extends AppCompatActivity {
    private RecyclerView rvShow;
    private MyAdapter myAdapter;
    private List<String> totalList = new ArrayList<>();
    private static final String TAG = "jasonwan";
    int currentPage = 0;

    private String url = "https://wanandroid.com/article/list/0/json";

    private static String getUrl(int page) {
        if (page < 0) {
            page = 0;
        }
        return "https://wanandroid.com/article/list/" + page + "/json";
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //将xml布局文件转化为View对象，利用了xml数据解析（SAX解析），利用反射创建View对象
        setContentView(R.layout.activity_recycler_view);
        //1.在布局文件里定义Recyclerview控件，然后通过findViewById进行初始化
        //RecyclerView相对于listview的优势：recyclerview复用了itemview
        rvShow = findViewById(R.id.rv_show);
        rvShow.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        //九宫格展示
        //rvShow.setLayoutManager(new GridLayoutManager(this, 3));
        //瀑布流展示
        //rvShow.setLayoutManager(new StaggeredGridLayoutManager());
        //2.创建adapter适配器
        myAdapter = new MyAdapter(totalList, this);
        //3、将adapter和recyclerview进行绑定
        rvShow.setAdapter(myAdapter);
        //    4、设置adapter的数据源
        mockData();
        //根据新数据源刷新UI
        myAdapter.notifyDataSetChanged();

        //    分页加载列表数据
        //    分页思路：判断recyclerview是否滑到底部，如果是，那么就加载下一页的数据，
        //    加载成功后添加到adapter的数据源里面去，最后通知recyclerview进行UI刷新
        rvShow.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //    判断是否滑到底部的两种方式：
                //    1、获取到屏幕当中第一个可见的item所在的position，firstItemPosition，
                //        2、获取当前屏幕显示了多少个item,visibleItemCount
                //        3、计算firstItemPosition+visibleItemCount跟adapter数据源的大小比较
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                int visibleItemCount = layoutManager.getChildCount();
                int totalCount = layoutManager.getItemCount();
                //Log.d(TAG, "onScrolled: firstVisibleItemPosition=" + firstVisibleItemPosition + ",visibleItemCount=" + visibleItemCount + ",totalCount=" + totalCount);
                //if ((firstVisibleItemPosition + visibleItemCount) >= totalCount && dy > 0) {
                //    Log.d(TAG, "onScrolled: 滑到底部了，dy=" + dy);
                //    //    已经滑到底部了，可以加载下一页的数据了
                //}


                //    2、第二种方式：
                if (!recyclerView.canScrollVertically(1)) {
                    Log.d(TAG, "onScrolled: 垂直方向不能滚动了，dy=" + dy);
                    //    已经滑到底部了，可以加载下一页的数据了
                    currentPage++;
                    getNetData(currentPage);
                }
            }
        });
        getNetData(currentPage);

        initListener();
    }

    private void initListener() {
        //给Recyclerview设置点击监听,发现recyclerview并没有相关给item单击设置监听器的方法，只能自己手写监听器
        myAdapter.setOnItemClickListener(new MyAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                //Toast.makeText(RecyclerViewActivity.this, "您点击了第" + position + "个item", Toast.LENGTH_SHORT).show();
                //WebViewActivity.gotoWebView(RecyclerViewActivity.this, "https://www.quectel.com/");
                List<String> list = myAdapter.getList();
                //局部刷新
                list.remove(position);
                //list.add(position, "我是Jason");
                myAdapter.notifyItemRemoved(position);
            }
        });
        //设置长按监听
        myAdapter.setOnItemLongClickListener(new MyAdapter.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(View view, int position) {
                //Toast.makeText(RecyclerViewActivity.this, "您长按了第" + position + "个item", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
    }

    private void getNetData(int currentPage) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(getUrl(currentPage))
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {

            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                String content = response.body().string();
                Log.d(TAG, "getNetDataByOkHttp: content=" + content);

                //更新adapter的数据源，然后通知recyclerview刷新UI
            }
        });
    }

    private void mockData() {
        for (int i = 0; i < 50; i++) {
            totalList.add("我是item" + i);
        }
    }


    //    rvShow.addOnScrollListener(new RecyclerView.OnScrollListener() {
    //    @Override
    //    public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
    //        super.onScrollStateChanged(recyclerView, newState);
    //    }
    //
    //    @Override
    //    public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
    //        super.onScrolled(recyclerView, dx, dy);
    //        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
    //        int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
    //        int visibleChildCount = layoutManager.getChildCount();
    //        int totalItemCount = layoutManager.getItemCount();
    //        if (firstVisibleItemPosition + visibleChildCount >= totalItemCount && dy > 0) {
    //            Log.d(TAG, "onScrolled: 到底啦,dy=" + dy);
    //        }
    //        //向上滚动为正数，向下滚动为负数
    //        if (!recyclerView.canScrollVertically(1)) {
    //            Log.d(TAG, "onScrolled: 不能向下滚动啦");
    //        }
    //    }
    //});
}